package leetcode;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class _1110 {
    /**
     * 删点成林
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    class Solution {
        public List<TreeNode> delNodes(TreeNode root, int[] to_delete) {
            List<TreeNode> ans = new ArrayList<TreeNode>();
            Set<Integer> s = new HashSet<>();
            for(int i:to_delete)s.add(i);
            if(dfs(ans,root,s)!=null) ans.add(root);
            return ans;
        }
        public TreeNode dfs(List<TreeNode> ans,TreeNode node,Set<Integer> s){
            if(node==null){
                return null;
            }
            node.left = dfs(ans,node.left,s);
            node.right = dfs(ans,node.right,s);
            if(!s.contains(node.val)){
                return node;
            }
            if(node.left!=null){
                ans.add(node.left);
            }
            if(node.right!=null){
                ans.add(node.right);
            }
            return null;
        }
    }
}
